<template>
  <!--委外管理-委外对账-->
  <section class="page outsource-reconciliation-manage">
    <data-form :model="model" @onSearch="refreshData" autoSearch>
      <!--输入区域-->
      <template slot="inputs">
        <el-form-item label="借据号" prop="caseNumber">
          <el-input v-model="model.caseNumber"></el-input>
        </el-form-item>
        <el-form-item label="批次号" prop="outBatch">
          <el-input v-model="model.outBatch"></el-input>
        </el-form-item>
        <el-form-item label="账单状态" prop="checkStatus">
          <el-select v-model="model.checkStatus" placeholder="请选择" clearable>
              <el-option v-for="{index,name,code} in $dict.getDictData('CheckStatus')" :key="index" :label="name" :value="code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入账时间" prop="entryTime">
          <el-date-picker type="daterange" :editable="false" v-model="model.entryTime" placeholder="选择日期时间" clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="委外方" prop="outId">
          <!-- <el-select v-model="model.outId" placeholder="请选择" clearable>
            <el-option v-for="item in outSourceList" :key="item.id" :label="item.outsName" :value="item.id"></el-option>
          </el-select> -->
          <select-department :specialOptions="specialOptions" v-model="model.outId"></select-department>
        </el-form-item>
      </template>
    </data-form>
    <!-- 数据列区 -->
    <data-box @onPageChange="refreshData" :data="dataSet" :selectionList.sync="selectionList" :page="pageService">
      <template slot="buttons">
        <el-button @click="exportBill" v-auth = "1020">对账单导出</el-button>
        <el-button @click="dialog.openBillCheck=true"  v-auth = "1021">对账单核对</el-button>
        <el-button @click="dialog.openCreatebill=true"  v-auth = "1022">生成账单</el-button>
        <el-button @click="dialog.uploadFile=true"  v-auth = "1023">导入还款记录</el-button>
        <el-button @click="exportTemplateInfo('CONTRAST_CHECK_BILL')">下载账单模板</el-button>
        <el-button @click="exportTemplateInfo('CONTRAST_REPAYMENT_RECORD')">下载还款模板</el-button>
      </template>
      <template slot="columns">
         <el-table-column label="操作" :min-width="$helper.getOperateWidth(1)">
          <template slot-scope="scope">
            <el-button type="text" @click="rowData=scope.row, dialog.openBillSurvey=true" :disabled="scope.row.checkStatus!=='CHECK_FAILURE'">调账</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="caseNumber" label="借据号" :min-width="$helper.getColumnWidth(6)">
          <template slot-scope="scope">
            <a  @click="openExecutionPage(scope.row)">{{scope.row.caseNumber}}</a>
          </template>
        </el-table-column>
        <el-table-column prop="outsName" label="委外方" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="outBatch" label="批次号" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="personalName" label="客户姓名" :min-width="$helper.getColumnWidth(5)">
        </el-table-column>
        <el-table-column prop="mobileNo" label="手机号" :formatter="(row)=>$filter.encryptPhone(row.mobileNo)" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="idCard" label="身份证号" :formatter="(row)=>$filter.encryptIDCardFour(row.idCard)" :min-width="$helper.getColumnWidth(6)">
        </el-table-column>
        <el-table-column prop="loanType" label="贷款类型" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="overduePeriod" label="逾期阶段" :min-width="$helper.getColumnWidth(3)">
        </el-table-column>
        <el-table-column prop="overdueDays" label="逾期天数" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="disOverduePeroid" label="分案时期数" :min-width="$helper.getColumnWidth(4)">
          <template slot-scope="scope">
            <span v-if="scope.row.disOverduePeriod">M{{scope.row.disOverduePeriod}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="outAmount" label="分案金额" :min-width="$helper.getColumnWidth(3)">
        </el-table-column>
        <el-table-column prop="repaymentAmount" label="还款金额" :min-width="$helper.getColumnWidth(3)">
        </el-table-column>
        <el-table-column prop="repaymentTime" label="还款时间" :min-width="$helper.getColumnWidth(5)" :formatter="(row) => $filter.dateTimeFormat(row.repaymentTime)">
        </el-table-column>
        <el-table-column prop="enterAmount" label="入账金额" :min-width="$helper.getColumnWidth(5)">
        </el-table-column>
        <el-table-column prop="entryTime" label="入账时间" :min-width="$helper.getColumnWidth(5)" :formatter="(row) => $filter.dateTimeFormat(row.entryTime)">
        </el-table-column>
        <el-table-column prop="outConfirmAmount" label="委托方确认金额" :min-width="$helper.getColumnWidth(5)">
        </el-table-column>
        <el-table-column prop="checkStatus" label="账单状态" :formatter="(row) => $filter.dictConvert(row.checkStatus,'CheckStatus')" :min-width="$helper.getColumnWidth(5)">
        </el-table-column>
        <el-table-column prop="adjustStatus" label="调账状态" :formatter="(row) => $filter.dictConvert(row.adjustStatus,'AdjustStatus')" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
      </template>
    </data-box>

    <!--生成账单-->
    <el-dialog title="生成账单" :visible.sync="dialog.openCreatebill" :close-on-click-modal="false" @open="() => this.$nextTick(() => this.$refs['create-bill'].refresh())" width="400px">
      <create-bill ref="create-bill" @close="dialog.openCreatebill=false;refreshData()" @refreshData="refreshData"></create-bill>
    </el-dialog>

    <!--对账单核对-->
    <el-dialog title="对账单核对" @close="dialog.openBillCheck=false" :visible.sync="dialog.openBillCheck" :close-on-click-modal="false" width="700px">
      <bill-check @close="dialog.openBillCheck=false;refreshData()" @refreshData="refreshData" ref="bill-check" :checkModel="checkModel"></bill-check>
    </el-dialog>
    
    <!-- 导入还款记录 -->
    <el-dialog title="导入还款记录" @close="dialog.uploadFile = false" :visible.sync="dialog.uploadFile" :close-on-click-modal="false" width="700px">
      <import-pay-record ref="import-pay-record" @close="dialog.uploadFile=false;refreshData()" @refreshData="refreshData"></import-pay-record>
    </el-dialog>
    
    <!--调帐-->
    <el-dialog title="调帐审核"  @close="$refs['bill-survey'].reset();dialog.openBillSurvey = false;" :visible.sync="dialog.openBillSurvey" :close-on-click-modal="false">
      <bill-survey @close="dialog.openBillSurvey=false;refreshData()" @refreshData="refreshData" ref="bill-survey" :rowData="rowData"></bill-survey>
    </el-dialog>

  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Auth, Layout, Dependencies } from "~/core/decorator";
import DataForm from "~/components/common/data-form.vue";
import DataBox from "~/components/common/data-box.vue";
import BillComponents from "~/components/outsource-manage/outsource-reconciliation-manage/index";
import FileUpload from "~/components/common/file-upload.vue";
import { PageService } from "~/utils/page.service";
import { SortService } from '~/utils/sort.service';
import { OutsourceService } from '~/services/domain-service/outsource.service';
import { OutsourceReconciliationManageService } from "~/services/domain-service/outsource-reconciliation-manage.service";
import { OpenExecutionData } from "~/config/types";
import { ApplyType, CASE_CHANNEL, CASE_HALT_CATEGORY, } from '~/config/enum.config';
import { Mutation, Getter, namespace, State } from 'vuex-class';
import SelectDepartment from "~/components/business-component/select-department.vue";
import { CommonService } from "~/utils/common.service";
import { SystemParamService } from "~/services/management-service/system-param.service";
const CollectionExecutionModule = namespace('collection-execution');

// @Auth(15)
@Layout('workspace')
@Component({
  components: {
    DataForm,
    DataBox,
    FileUpload,
    SelectDepartment,
    ...BillComponents
  },
})
export default class OutsourceReconciliationManageIndex extends Vue {
  @Dependencies(OutsourceReconciliationManageService)
  private outsourceReconciliationManageService: OutsourceReconciliationManageService;
  @Dependencies(SystemParamService) private systemParamService: SystemParamService;
  @Dependencies(OutsourceService)
  private outsourceService: OutsourceService;
  @Dependencies(PageService)
  private pageService: PageService;
  @Dependencies(SortService)
  private sortService: SortService;
  @CollectionExecutionModule.Action private openCollectionExecution;
  @State private outSourceList;

  private model: any = {
    outBatch:'',
    caseNumber:'',
    outId:'',
    checkStatus:'',
    entryTime:[],

  }
  // 数据列表
  private dataSet: any[] = [];
  // 弹框控制
  private dialog: any = {
    openBillCheck: false,
    openCreatebill: false,
    openBillSurvey: false,
    openImportPayRecord: false,
    uploadFile: false,
  };

  private checkModel: any = {};
  
  private fileList: any = []

  private selectionList: any[] = [];
  private check: any = {};
  private rowData: any = null
  private recCheckData: any = {}; //调账的参数
  private specialOptions:any[] = []


  private refreshData() {
    this.outsourceReconciliationManageService.caseOutContrastList(this.model,this.pageService).subscribe(
      data => {
        this.dataSet = data
        if(this.dataSet){
          this.dataSet.forEach(x=>{
            x.overduePeriod>12?x.overduePeriod = 'M12+':x.overduePeriod = 'M'+x.overduePeriod
          })
        }
      }
    )
  }
  //模板导出
  private exportTemplateInfo(val) {
    this.systemParamService
      .getTemplateUrl(val)
      .subscribe(data => this.$common.downloadFile(data));
  }
  /**
   * 对账单导出
   */
  private exportBill(){
    if (this.dataSet.length === 0) {
      this.$message.info("暂无可导出的数据")
      return
    }
    let text: string = ""
    let caseIds: any[] = []
    const sum = this.selectionList.length;
    
    if (sum !== 0) {
      text = "已选择"+sum+"个案件，确认导出对账单?"
      caseIds = this.selectionList.map(v => v.id)
    } else if(this.validateModel()) {
      text = "此操作将按照搜索过滤条件导出对账单，确认导出?"
    } else {
      text = "此操作将导出所有对账单，确认导出?"
    }
    const params = {
      caseIds,
      batchNumber:this.model.batchNumber,
      checkStatus:this.model.checkStatus,
      entryTimeStart:this.model.entryTime[0],
      entryTimeEnd:this.model.entryTime[1],
      outId:this.model.outsName
    }
    this.$confirm(text, "导出对账单", {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      this.confirmExport(params)
    }).catch(() => {
      this.$message.success("已取消")
    })
  }


  //获取委外部门不包括律所
  private getOuterSource() {
    this.outsourceService.getOuterSource().subscribe(
      data =>{ this.specialOptions = CommonService.generateTreeData(data, {
        keyName: 'id',
        parentKeyName: 'parentId'
      })
      // data =>{console.log(data,"data")
    })
  }
  private validateModel() {
    return this.model.batchNumber || this.model.caseNumber || this.model.outId 
    || this.model.checkStatus || this.model.entryTime.length !== 0
  }

  /**
   * 确认导出对账单
   */
  private confirmExport(data: any) {
    this.outsourceReconciliationManageService.exportBills(data, true).subscribe(
      data => this.$common.downloadFile(data.url)
    )
  }

  /**
   * 进入查看执行页
   */
  private openExecutionPage(row) {
    this.openCollectionExecution(new OpenExecutionData(row.id, row.caseNumber, CASE_CHANNEL.OUTER, true,true))
  }

  private mounted() {
    this.refreshData()
    this.getOuterSource()
  }


}
</script>

<style lang="less" >
  .btn-group{
    display: flex;
    justify-content: flex-end;
    padding-top: 20px;
  }
</style>
